import { apiUrl, ossApiUrl } from './url'
import store from '../store/index'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { formatParams, toLogin } from '.'

const request = async ({
  url,
  data,
  auth = true,
  showLoading,
  method = 'GET',
  type = 'api'
}) => {
  if (auth && !store.state.user.token) {
    toLogin()
    throw new Error('用户未登录')
  }

  if (showLoading) {
    Taro.showLoading({
      mask: true,
      title: '加载中'
    })
  }

  const { data: res } = await Taro.request({
    url: type === 'api' ? apiUrl(url) : ossApiUrl(url),
    data,
    method,
    header: {
      'content-type': 'application/json', // 默认值
      appToken: auth ? store.state.user.token : ''
    }
  })
  if (showLoading) {
    Taro.hideLoading()
  }
  if (res.success) {
    return res
  } else {
    if (res.error_no === 402) {
      toLogin()
      throw new Error('用户未登录')
    }

    Taro.showToast({
      title: res.error_msg,
      icon: 'none',
      duration: 2000
    })
    throw new Error(res.error_msg)
  }
}

export const upload = async ({ url, filePath, name, formData }) => {
  const res = await Taro.uploadFile({
    url,
    filePath,
    name,
    formData
  })
  return JSON.parse(res.data)
}

export default request
